﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using blackhouse.BlackApart.Business.PushMails;
using blackhouse.BlackApart.Business;
using System.Net.Mail;

namespace blackhouse.BlackApart.Actions {
    public class PushMailAction : Action {

        #region Fields

        private IPushMail pushMail;
        private SmtpClient client = new SmtpClient();
        private MailMessage message = new MailMessage();
        #endregion

        #region Methods

        public override void Run() {
            if (!string.IsNullOrWhiteSpace(pushMail.Title)) {
                try {
                    this.SendMail();
                    this.pushMail.MarkAsSended();
                    Log.AppendToMessage("Wysłano do: " + string.Join("; ", this.pushMail.To));
                } catch(Exception e) {
                    Log.AppendToMessage(e.Message);
                }
            }

        }

        private void SendMail() {
            this.message.Subject = this.pushMail.Title;
            this.message.Body = this.pushMail.Content;
            this.message.IsBodyHtml = this.pushMail.IsHtml;
            foreach (string to in this.pushMail.To) {
                this.message.To.Add(to);
            }
            this.client.EnableSsl = this.client.Port == 587 || this.client.Port == 465;
            this.client.Send(this.message);
        }

        public override void Initialize(string initializeData) {
            if (string.IsNullOrEmpty(initializeData)) return;
            string[] parts = initializeData.Split(',');
            int id;
            if (parts.Length >= 3 && Int32.TryParse(parts[2], out id)) {
                this.pushMail = Factory.Instance().MakePushMail(id);
            }
            base.Initialize(initializeData);
        }

        #endregion

    }
}
